<?php

namespace frontendx\controllers;

use yii\web\Controller;
use Yii;
use yii\helpers\ArrayHelper;
use common\models\User;
use common\components\MTools;
use yii\helpers\Json;
use common\components\OperateEvent;
use frontendw\models\WB_UserAccountHy;
use frontendx\models\WB_UserDrawalRecord;

/* use Yii;
  use frontendm\models\LoginForm;
  use frontendm\models\PasswordResetRequestForm;
  use frontendm\models\ResetPasswordForm;
  use frontendm\models\SignupForm;
  use yii\base\InvalidParamException;
  use yii\web\BadRequestHttpException;
  use yii\web\Controller;
  use yii\filters\VerbFilter;
  use yii\filters\AccessControl; */

/**
 * WeChatController controller
 */
class WechatController extends Controller {

    public $xmlResult;
    private $eventType; //事件类型
    private $eventKey; //事件唯一标识
    private $msgType; //请求类型
    private $openid;
    private $msgContent;
    private $cacheTime = 360;
    private $_user;

    /*
     * 获取微信请求相关信息
     */

    protected function initConfigInfo() {
        $this->msgType = ArrayHelper::getValue($this->xmlResult, "MsgType");
        $this->eventType = ArrayHelper::getValue($this->xmlResult, "Event");
        $this->eventKey = ArrayHelper::getValue($this->xmlResult, "EventKey");
        $this->openid = ArrayHelper::getValue($this->xmlResult, "FromUserName");
        $this->msgContent = ArrayHelper::getValue($this->xmlResult, "Content");
    }

    /*
     * 获取用户信息模型 
     */

    private function getUser() {
        if (!$this->_user) {
            $this->_user = User::find()->where("wxopenid=:wxopenid and role=2", [":wxopenid" => $this->openid])->one();
        }
        return $this->_user;
    }

    /*
     * 菜单点击操作
     */

    protected function clickMenuOperate() {
        switch ($this->eventKey) {
            //点击客服事件处理
            case "kefu":
                $content = "亲。如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
                $this->replayTextMessage($content);
                break;
            //点击提交任务
            case "PIC_000":
                //获取要提交的任务信息
                $taskModel = \frontendx\models\WB_UserTaskOperate::getWXCansubmitOneOfTask($this->openid);
                if ($taskModel) {
                    //缓存记录提交任务的ID
                    \yii::$app->cache->set($this->openid . "_taskid", $taskModel["id"] . "_" . $taskModel["taskid"] . "_" . $taskModel["sample_figure_count"], $this->cacheTime);
                    //模板带图片，链接提示
                    $data = [
                        'touser' => $this->openid,
                        'msgtype' => 'news',
                        'news' => [
                            'articles' => [
                                [
                                    'description' => '请您查看任务图片，是否您要提交的任务，直接在公众号传入图片即可完成任务',
                                    'url' => \yii\helpers\Url::toRoute(["task/taskdetail", "taskid" => $taskModel["taskid"], "id" => $taskModel["id"]], true),
                                    'picurl' => MTools::getQiniuImagepath($taskModel["sample_figure"])
                                ]
                            ]
                        ]
                    ];
                    Yii::$app->wechat->sendMessage($data);
                } else {
                    $content = '你当前没有正在进行的任务。点击菜单【首页】进入接新的任务吧！';
                    $this->replayTextMessage($content);
                }
                break;
            //重新提交认为
            case "PIC_002":
                //获取要提交的任务ID
                $taskstring = \yii::$app->cache->get($this->openid . "_taskid");
                if ($taskstring) {
                    list($operid, $taskid, $sample_figure_count) = explode("_", $taskstring);
                    \yii::$app->cache->delete($this->openid . "_image_" . $taskid);
                    $content = '图片重置成功';
                } else {
                    $content = "你当前没有正在进行的任务。点击菜单【首页】进入接新的任务吧！";
                }
                $this->replayTextMessage($content);
            //提现说明
            case "tixian":
                if ($this->getUser() instanceof User) {
                    $content = "您目前的可提现金额:" . ($this->getUser()->wallet ? Yii::$app->formatter->asDecimal($this->getUser()->wallet->amount) : 0) . "，满1元以上才可以提现，可回复格式: TX@金额 进行提现 例如一元: TX@1";
                    $content .= "\n";
                    $content .= "------------\n";
                    $content .= "为了方便财务 审核，提现以“元”整数为准如有不便，敬请见谅！";
                } else {
                    $content = "已有账号请发送bd@账号@密码进行公众号绑定。例如:bd@haoye@888888";
                }
                $this->replayTextMessage($content);
                break;
            default:
                break;
        }
    }

    /*
     * 关注公众号，自动创建账号
     */

    protected function subscribeRem() {
        if (!$this->getUser()) {
            list($prefix, $store_id) = explode('_', $this->xmlResult->EventKey);
            $invite_code = "Y55970";
            if ($prefix === "qrscene" && !empty($store_id)) {
                //获取推荐人的信息
                $referModel = User::findOne($store_id);
                if ($referModel->froststatus == 0) {
                    $invite_code = $referModel->my_code;
                }
            }
            $trans = Yii::$app->db->beginTransaction();
            try {

                //获取微信信息
                $openInfo = Yii::$app->wechat->getUserInfo($this->openid);
                $user = new User();
                $user->username = $openInfo["nickname"];
                $user->role = 2;
                $user->my_code = MTools::makeOnlyNumber();
                $user->wxopenid = $this->openid;
                $user->setPassword(111111);
                $user->generateAuthKey();
                $user->generatePasswordResetToken();
                if ($user->save()) {
                    //保存基本信息
                    $userprofile = new \common\models\UserProfile();
                    $userprofile->userid = $user->id;
                    $userprofile->username = $user->username;
                    $userprofile->invite_code = $invite_code;
                    $userprofile->truename = $user->username;
                    $userprofile->headerimg = $openInfo["headimgurl"];
                    if ($userprofile->save()) {
                        $useraccount = new \common\models\UserAccountHy();
                        $useraccount->userid = $userprofile->userid;
                        $useraccount->amount = 0;
                        $useraccount->offline_amount = 0;
                        if ($useraccount->save()) {
                            $trans->commit();
                        }
                    }
                }
            } catch (Exception $ex) {
                $trans->rollBack();
                throw new \yii\web\NotFoundHttpException($ex);
            }
        }
    }

    /*
     * 微信发送消息的链接地址
     */

    public function actionValid() {
        $wechat = Yii::$app->wechat;
        $this->xmlResult = $wechat->parseRequestXml();
        if ($this->xmlResult) {
            $this->initConfigInfo();
            //判断请求的是否为事件
            if ($this->msgType == 'event') {
                //判断事件类型
                switch ($this->eventType) {
                    //关注处理
                    case 'subscribe':
                        $this->subscribeRem();
                        $content = "欢迎您关注皓夜众包平台公众号，自动注册账号成功！点击菜单首页进入平台轻松自由，随时随地轻松赚钱，有问题请加QQ群：52355521,私聊咨询客服~n";
                        $this->replayTextMessage($content);
                        break;
                    //click点击事件
                    case 'CLICK':
                        $this->clickMenuOperate();
                        break;
                    default:
                        break;
                }
            } else {
                $this->NotEventReplay();
            }
        }
    }

    /*
     * 被动回复文本消息
     * @params $content
     */

    private function replayTextMessage($content) {
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            </xml>";
        $resultStr = sprintf($textTpl, ArrayHelper::getValue($this->xmlResult, "FromUserName"), ArrayHelper::getValue($this->xmlResult, "ToUserName"), time(), "text", $content);
        echo $resultStr;
    }

    /*
     * 被动消息回复，非事件
     */

    private function NotEventReplay() {
        $replayResult = explode("@", $this->msgContent);
        $argcount = count($replayResult);
        if ($argcount > 2) {
            $username = substr(substr($this->msgContent, 0, strrpos($this->msgContent, "@")), strpos($this->msgContent, "@") + 1);
            $bd = $replayResult[0];
            $password = $replayResult[$argcount - 1];
            if ($bd == "bd") {
                //微信绑定账号
                $content = $this->userBindOpenID($username, $password);
            } else {
                $content = "亲，请发送bd@账号@密码进行公众号绑定。例如:bd@haoye@888888";
            }
        } else if ($argcount == 2) {
            $key = $replayResult[0];
            $value = $replayResult[1];
            if ($this->getUser() instanceof User) {
                if ($this->_user->froststatus == 0) {
                    if ($key == "TX") {
                        $content = $this->userDrawalCash($value);
                    } else {
                        $content = "亲。如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
                    }
                } else {
                    $content = "亲。您的账号已被冻结或已被封，如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
                }
            } else {
                $content = "亲，对不起，您还没有绑定账号，已有账号请发送bd@账号@密码进行公众号绑定。例如:bd@haoye@888888";
            }
        } else if ($this->msgType == 'image') {
            //获取要提交的任务ID
            $taskstring = \yii::$app->cache->get($this->openid . "_taskid");
            if ($taskstring) {
                list($operid, $taskid, $sample_figure_count) = explode("_", $taskstring);
                $mediald = ArrayHelper::getValue($this->xmlResult, "MediaId");
                $result = Yii::$app->wechat->getMedia($mediald);
                if ($result) {
                    //查询缓存
                    $cache_task_image = \yii::$app->cache->get($this->openid . "_image_" . $taskid);
                    if (!$cache_task_image) {
                        $cache_task_image = [];
                    }
                    array_push($cache_task_image, $result);
//                    //加入缓存
                    \yii::$app->cache->set($this->openid . "_image_" . $taskid, $cache_task_image, $this->cacheTime);
////                    //判断会员是否已经上传足够的任务图片
                    $num = $sample_figure_count - count($cache_task_image);
                    if ($num == 0) {
                        //提交任务
                        $OperateEvent = new OperateEvent();
                        $content = $OperateEvent->completeTasks($cache_task_image, $operid);
                        //上传完成删除值
                        \yii::$app->cache->delete($this->openid . "_taskid");
                        \yii::$app->cache->delete($this->openid . "_image_" . $taskid);
                    } else {
                        $content = "亲，需要上传" . $sample_figure_count . "张图，您还差" . $num . "张图未上传无法提交！";
                    }
                } else {
                    $content = "提取图片失败";
                }
            } else {
                $content = "您发了张图片，可是我不明白是什么意思。如果您是想提交任务截图，请先点击下方的【交任务】菜单【提交任务】，再提交截图哦！";
            }
        }
        $this->replayTextMessage($content);
    }

    /*
     * 微信绑定账号
     * @params $username
     * @params  $password
     */

    protected function userBindOpenID($username, $password) {
        if ($username && $password) {
            $useropen = User::find()->where("wxopenid=:wxopenid and role=2", [":wxopenid" => $this->openid])->one();
            if (!$useropen instanceof User) {
                $user = User::find()->where("username=:username and role=2", [":username" => $username])->one();
                if ($user instanceof User) {
                    if ($user->validatePassword($password)) {
                        if ($user->wxopenid) {
                            $content = "您输入的帐号已绑定过了：" . $username;
                        } else {
                            $user->wxopenid = $this->openid;
                            if ($user->save()) {
                                $content = "已经成功为你绑定帐号[" . $user->username . "]。点击下方菜单，开始体验吧！";
                            } else {
                                $content = "对不起，您绑定失败";
                            }
                        }
                    } else {
                        $content = "对不起，您输入的账号或密码不正确";
                    }
                } else {
                    $content = "对不起，您输入的账号不存在";
                }
            } else {
                $content = "此微信号已绑定过帐号" . $useropen->username; //"亲。您已经绑定了".."账号。一个微信号只能绑定一个平台账号！";
            }
        } else {
            $content = "亲。如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
        }
        return $content;
    }

    /*
     * 提现
     * @params $value 提现金额
     */

    protected function userDrawalCash($value) {
        $value = (int) $value;
        if (!is_numeric($value) || !is_int($value) || $value <= 0) {
            $content = "亲，您输入的金额必须是整数才行呢";
        } else if ($value < MTools::getYiiParams("rebate_amount")) {
            $content = "您的帐户金额:" . MTools::getYiiParams("rebate_amount") . "皓币不足以提现。必须满1元以上才可以提现。赶紧去做任务吧~";
        } else {
            //判断是否存在金额账户
            if ($this->_user->wallet) {
                if ($value > $this->_user->wallet->amount) {
                    $content = "亲，对不起提现的金额大于了您的账户余额";
                } else {
                    $res = $this->payment($this->openid, $value, $this->_user->id);
                    if ($res === true) {
                        $content = "成功申请提现[" . $value . "]元。\n\n";
                        $content .= "系统会在1分钟内将佣金直接转入您的微信零钱账户，同时您会收到微信支付到账通知。";
                    } else {
                        $content = $res;//"系统繁忙请稍后再试";
                    }
                }
            } else {
                $content = "您的还没有在平台领过任务，不存在金额账户哦，快去领任务提现吧！";
            }
        }
        return $content;
    }

    /*
     * 创建菜单
     */

    public function actionCreatemenu() {
        $buttons = [
            [
                'name' => '交任务',
                'sub_button' => [
                    [
                        "type" => "click",
                        "name" => "提交任务",
                        "key" => "PIC_000"
                    ],
                    [
                        "type" => "click",
                        "name" => "重新提交",
                        "key" => "PIC_002"
                    ]
                ]
            ],
            [
                'name' => '首页',
                "type" => "view",
                "url" => \yii\helpers\Url::toRoute(["site/index"], true),
            ],
            [
                'name' => '个人中心',
                'sub_button' => [
                    [
                        "type" => "view",
                        "name" => "个人信息",
                        "url" => \yii\helpers\Url::toRoute(["profile/info"], true),
                    ],
                    [
                        "type" => "click",
                        "name" => "提现说明",
                        "key" => "tixian"
                    ],
                    [
                        "type" => "click",
                        "name" => "客服中心",
                        "key" => "kefu"
                    ]
                ]
            ]
        ];
        $result = Yii::$app->wechat->createMenu($buttons);
        if ($result) {
            echo "创建菜单成功";
        }
    }

    public function actionTuisong() {

        $urlx = 'http://wx.toupiao518.com/wechat/tuisong.html';
        if ($code = Yii::$app->request->get("code")) {
            $openid_info = Yii::$app->wechat->getOauth2AccessToken($code);
//                $data = [
//                    'touser'=>$openid_info['openid'],
//                    'msgtype'=>'text',
//                    'text'=>["content'=>'hello world <a href='http://www.baidu.com'>点击查看详情</a>"]
//                ];
            $data = [
                'touser' => $openid_info['openid'],
                'msgtype' => 'news',
                'news' => [
                    'articles' => [
                        [
                            'title' => '标题',
                            'description' => '内容',
                            'url' => 'http://www.baidu.com',
                            'picurl' => 'http://www.hishop.com.cn/uploads/150914/21678-150914112244436.jpg'
                        ]
                    ]
                ]
            ];

            $result = Yii::$app->wechat->sendMessage($data);
            var_dump($result);
            die;
            if ($result)
                echo '成功';
        } else {
            $url = Yii::$app->wechat->getOauth2AuthorizeUrl($urlx);
            header("Location:$url");
        }
    }

    public function payment($openid, $money, $userid) {
        //进行转账
        header("Content-type: text/html; charset=utf-8");
        $data['mch_appid'] = 'wxd75226638997e459'; //商户的应用appid
        $data['mchid'] = '1484565582'; //商户ID
        $data['nonce_str'] = $this->unicode(); //$this->unicode();//这个据说是唯一的字符串下面有方法

        $data['partner_trade_no'] = time(); //.time();//这个是订单号。

        $data['openid'] = $openid; //这个是授权用户的openid。。这个必须得是用户授权才能用

        $data['check_name'] = 'NO_CHECK'; //这个是设置是否检测用户真实姓名的

        $data['re_user_name'] = '123'; //用户的真实名字

        $data['amount'] = $money * 100; //提现金额 100为1元

        $data['desc'] = '皓夜科技提现'; //订单描述

        $data['spbill_create_ip'] = $_SERVER['SERVER_ADDR']; //这个最烦了，，还得获取服务器的ip

        $secrect_key = 'aFwJDcQZ61nGDZ4mi5sZWTkizat0eIgX'; ///这个就是个API密码。32位的。。随便MD5一下就可以了

        $data = array_filter($data);

        ksort($data);

        $str = '';

        foreach ($data as $k => $v) {

            $str .= $k . '=' . $v . '&';
        }

        $str .= 'key=' . $secrect_key;

        $data['sign'] = md5($str);
        $xml = $this->arraytoxml($data);
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';

        $res = $this->curl($xml, $url);
        $return = $this->xmltoarray($res);

        if ($return['return_code'] == 'SUCCESS' && $return['result_code'] == 'SUCCESS') {
            $trans = Yii::$app->db->beginTransaction();
            try {
                $user = User::findOne($userid);

                //返现推荐账号佣金
                $refuser = User::find()->where("my_code=:invite_code", [":invite_code" => $user->userprofile->invite_code])->one();
                if ($refuser instanceof User) {
                    $userpayrecord = new \frontendm\models\WB_UserPayRecordHy();
                    $userpayrecord->userid = $refuser->id;
                    $userpayrecord->type = 1;
                    $userpayrecord->class_type = 1;
                    $userpayrecord->amount = $money * 0.05;
                    $userpayrecord->is_drawal = 1;
                    $userpayrecord->description = "提现返还佣金￥" . $money * 0.05;
                    $rebateRecord = new \frontendm\models\WB_UserRebateRecord();
                    $rebateRecord->fuserid = $user->id;
                    $rebateRecord->fusername = $user->username;
                    $rebateRecord->tuserid = $refuser->id;
                    $rebateRecord->tusername = $refuser->username;
                    $rebateRecord->rebate_amount = $money * 0.05;
                    $rebateRecord->amount = $money;
                    if ($userpayrecord->save() && $rebateRecord->save()) {
                        if ($refuser->wallet) {
                            //$refuser->wallet->amount = $refuser->wallet->amount + 1;
                            $refuser->wallet->offline_amount = $refuser->wallet->offline_amount + $money * 0.05;
                            $refuser->wallet->amount = $refuser->wallet->amount + $money * 0.05;
                            $refuser->wallet->save();
                        } else {
                            $useraccount = new \frontendm\models\WB_UserAccountHy();
                            $useraccount->userid = $refuser->id;
                            //$useraccount->amount = 1;
                            $useraccount->offline_amount = $money * 0.05;
                            $useraccount->amount = $money * 0.05;
                            $useraccount->yet_drawal_amount = 0;
                            $useraccount->save();
                        }
                    }
                }

                $record = new \frontendm\models\WB_UserDrawalRecord();
                $record->partner_trade_no = $return["partner_trade_no"];
                $record->payment_no = $return["payment_no"];
                $record->payment_time = $return["payment_time"];
                $record->amount = $money;
                $record->wxopenid = $openid;
                $record->userid = $userid;
                if ($record->save()) {
                    //$user->wallet->can_drawal_amount = $user->wallet->can_drawal_amount - $money;
                    $user->wallet->amount = $user->wallet->amount - $money;
                    $user->wallet->yet_drawal_amount = $user->wallet->yet_drawal_amount + $money;
                    if ($user->wallet->save()) {
                        $trans->commit();
                        return true;
                    }
                }
            } catch (Exception $ex) {
                $trans->rollBack();
                throw new \yii\web\NotFoundHttpException;
            }
            //申请提现成功
        } else {
            return $return['return_msg'];
        }
        // echo getcwd().'/cert/apiclient_cert.pem';die;
    }

    public function xmltoarray($xml) {

        //禁止引用外部xml实体 

        libxml_disable_entity_loader(true);

        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

        $val = json_decode(json_encode($xmlstring), true);

        return $val;
    }

    public function curl($param = "", $url) {

        $postUrl = $url;

        $curlPost = $param;

        $ch = curl_init();                                      //初始化curl

        curl_setopt($ch, CURLOPT_URL, $postUrl);                 //抓取指定网页

        curl_setopt($ch, CURLOPT_HEADER, 0);                    //设置header

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);            //要求结果为字符串且输出到屏幕上

        curl_setopt($ch, CURLOPT_POST, 1);                      //post提交方式

        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);           // 增加 HTTP Header（头）里的字段 

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);        // 终止从服务端进行验证

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_SSLCERT, getcwd() . '/cert/apiclient_cert.pem'); //这个是证书的位置

        curl_setopt($ch, CURLOPT_SSLKEY, getcwd() . '/cert/apiclient_key.pem'); //这个也是证书的位置

        $data = curl_exec($ch);                                 //运行curl

        curl_close($ch);

        return $data;
    }

    public function unicode() {

        $str = uniqid(mt_rand(), 1);

        $str = sha1($str);

        return md5($str);
    }

    public function arraytoxml($data) {

        $str = '<xml>';

        foreach ($data as $k => $v) {

            $str .= '<' . $k . '>' . $v . '</' . $k . '>';
        }

        $str .= '</xml>';

        return $str;
    }

}
